package thulearningcore.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.CharBuffer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TLURLConnection {
	private static String defaultCharset = "utf-8";
	private static int defaultConnectTimeout = 30000;
	private static int defaultReadTimeout = 60000;
	private static int defaultFileTimeout = 60000;

	public static String post(String url) throws Exception {
		return post(new URL(TLURLEncoder.encode(url, defaultCharset)));
	}

	public static String post(URL url) throws Exception {
		return post(url, defaultCharset);
	}

	public static String post(String url, String charset) throws Exception {
		return post(new URL(TLURLEncoder.encode(url, charset)), charset);
	}

	public static String post(URL url, String charset) throws Exception {
		return post(url, charset, true);
	}

	public static String post(String url, boolean saveCookies) throws Exception {
		return post(new URL(TLURLEncoder.encode(url, defaultCharset)),
				saveCookies);
	}

	public static String post(URL url, boolean saveCookies) throws Exception {
		return post(url, defaultCharset, saveCookies);
	}

	public static String post(String url, String charset, boolean saveCookies)
			throws Exception {
		return post(new URL(TLURLEncoder.encode(url, charset)), charset,
				saveCookies);
	}


	public static String post(URL url, String charset, boolean saveCookies)
			throws Exception {
		HttpURLConnection httpc = (HttpURLConnection) url.openConnection();
		httpc.setConnectTimeout(defaultConnectTimeout);
		httpc.setReadTimeout(defaultReadTimeout);

		httpc.addRequestProperty("Cookie", TLCookieManager.getInstance()
				.getCookies());
		httpc.connect();
		if (saveCookies)
			TLCookieManager.getInstance().addCookieFromURLConnection(httpc);
		InputStream is = httpc.getInputStream();
		InputStreamReader reader = new InputStreamReader(is, charset);
		BufferedReader breader = new BufferedReader(reader, 65536);

		StringBuilder sb = new StringBuilder(65536);
		CharBuffer charBuffer = CharBuffer.allocate(65536);
		while (breader.read(charBuffer) != -1) {
			if (charBuffer.length() == 0) {
				charBuffer.flip();
				sb.append(charBuffer);
			}
		}
		charBuffer.flip();
		sb.append(charBuffer);
		String result = sb.toString();

		breader.close();
		reader.close();
		return result;
	}

	public static String download(String url, String path, String filename)
			throws Exception {
		return download(new URL(url), path, filename);
	}
	
	
	public static String download(URL url, String path, String filename)
			throws Exception {

		HttpURLConnection httpc = (HttpURLConnection) url.openConnection();
		httpc.setConnectTimeout(defaultConnectTimeout);
		httpc.setReadTimeout(defaultFileTimeout);
		httpc.addRequestProperty("Cookie", TLCookieManager.getInstance()
				.getCookies());
		TLCookieManager.getInstance().addCookieFromURLConnection(httpc);
		httpc.connect();

		String remoteFile = httpc.getHeaderField("Content-Disposition");
		Matcher m = Pattern.compile("filename=\"[^.]*.([^\"]*)").matcher(
				remoteFile);

		if (!m.find()) {
			return null;
		}
		String suf = m.group(1);

		File file = new File(path + filename + "." + suf);
		if (!file.exists()) {
			if (!file.createNewFile())
				return null;
		}
		BufferedInputStream is = new BufferedInputStream(
				httpc.getInputStream(), 65536);
		FileOutputStream fos = new FileOutputStream(file);

		byte[] buf = new byte[65536];
		int len;
		while ((len = is.read(buf)) != -1) {
			fos.write(buf, 0, len);
		}
		is.close();
		fos.close();

		return filename + "." + suf + "\0" + httpc.getContentType();
	}
}
